import { Container } from "typedi";
import { AssetsService } from "../../repositories/assets/AssetsService";
import type { Asset } from "../../repositories/assets/entity";

export type AssetsLocation = {
  id: number;
  name: string;
  assets: Asset[];
};
const SAFE_ASSETS: AssetsLocation = {
  id: 2004,
  name: "安全资产",
  assets: [],
};

export const useAssets = () => {
  const assetsService = Container.get(AssetsService);
  const fetch = async (playerIds: number[]) => {
    const playerAssets: Asset[] = [];
    for (const playerId of playerIds) {
      playerAssets.push(...(await assetsService.all(playerId)));
    }
    return groupByStation(playerAssets);
  };

  const groupByStation = (playerAssets: Asset[]) => {
    const rootLocations = new Map<number, AssetsLocation>();
    rootLocations.set(SAFE_ASSETS.id, SAFE_ASSETS);
    for (const asset of playerAssets) {
      let location = rootLocations.get(asset.location_id);
      if (!location) {
        location = {
          id: asset.location_id,
          name: asset.location?.name ?? "无法访问",
          assets: [],
        };
        rootLocations.set(location.id, location);
      }
      if (location.assets!.some((a) => a.item_id === asset.item_id)) {
        continue;
      }
      location.assets!.push(asset);
    }
    return Array.from(rootLocations.values());
  };
  return { fetch };
};
